import axios from "axios";
import { useUserStore } from '@/store/user'
import request from "@/utils/request";
import { baseUrl } from '@/env.config'
/**
 * 获取文件的信息
 * @param service
 * @param id
 * @returns {Promise<AxiosResponse<any>>}
 */
export function download(service, id) {
    return request({
        url: service + "/fileController/getPreviewUrl?id=" + id,
        method: 'get',
        autoUntie: false,
    });
}
/**
 * 下载文件
 * @param fileId 文件的主键
 * @param fileName 文件的名称
 * @param service 服务
 * @returns {Promise<void>}
 */

export async function downloadFile(fileId, fileName, service) {
    download(service, fileId).then((res) => {
        let fTyeps = '';
        const startIndex = res.obj.lastIndexOf(".");
        const endIndex = res.obj.indexOf("?");
        if (startIndex !== -1 && endIndex !== -1 && endIndex > startIndex) {
            fTyeps = res.obj.substring(startIndex, endIndex);
        }
        axios.get(res.obj, {
            responseType: "blob",
        })
            .then((res) => {
                const blob = new Blob([res.data], { type: "application/octet-stream" });
                const fileNameType = fileName + fTyeps;
                console.log(fTyeps);
                if (window.navigator.msSaveOrOpenBlob) {
                    navigator.msSaveOrOpenBlob(blob, fileNameType);
                } else {
                    let link = document.createElement("a");
                    const href = URL.createObjectURL(blob);
                    link.href = href;
                    link.style.display = "none";
                    link.setAttribute('download', fileNameType);
                    document.body.appendChild(link);
                    link.click();
                    URL.revokeObjectURL(link.href);
                }
            });
    });
}

/**
 * 下载工卡
 * @param params 规程任务主键。多个以逗号分隔
 * @param loading 遮罩层
 * @returns {Promise<void>}
 */
export async function downloadCard(params, loading) {
    const { token } = useUserStore()
    isRef(loading) && (loading.value = true)
    axios({
        method: "get",
        url:
            baseUrl +
            "/mes/processCardController/downloadCardFile",
        responseType: "blob",
        params: params,
        headers: {
            "Content-Type": "application/json;application/octet-stream",
            "h-authorization-token": token,
        },
    }).then((res) => {
        let fileName = window.decodeURI(
            res.headers["content-disposition"].split(";")[1].split("=")[1],
            "UTF-8"
        ); //获取压缩包文件名称
        let blob = new Blob([res.data], { type: "application/zip" });
        let url = window.URL.createObjectURL(blob);
        const link = document.createElement("a"); // 创建a标签
        link.href = url;
        link.download = fileName; // 重命名文件
        link.click();
        URL.revokeObjectURL(url); // 释放内存
    }).catch((err) => {
        ElMessage.error(err.message)
    }).finally(() => {
        isRef(loading) && (loading.value = false)
    });
}

/**
 * 使用Post下载文件
 * @param url 路径
 * @param data 数据
 * @param loading 加载栏
 * @returns {Promise<void>} 没有返回
 */
export async function downloadByPost(url, data, loading) {
    const { token } = useUserStore()
    axios({
        method: 'post',
        url:
            baseUrl +
            url,
        responseType: "blob",
        data: data,
        headers: {
            "Content-Type": "application/json;application/octet-stream",
            "h-authorization-token": token,
        },
    }).then((res) => {
        loading.close();
        let fileName = window.decodeURI(
            res.headers["content-disposition"].split(";")[1].split("=")[1],
            "UTF-8"
        ); //获取文件的名称
        let contentType = res.headers['content-type'];
        let blob = new Blob([res.data], { type: contentType });
        let url = window.URL.createObjectURL(blob);
        const link = document.createElement("a"); // 创建a标签
        link.href = url;
        link.download = fileName; // 重命名文件
        link.click();
        URL.revokeObjectURL(url); // 释放内存
    }).catch((err) => {
        ElMessage.error(err.message)
    }).finally(() => {
        isRef(loading) && (loading.value = false)
    });
}

export const fileAccept = (e) => {
    let text;
    switch (e) {
        case "application/msword":
            text = ".doc";
            break;
        case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
            text = ".docx";
            break;
        case "application/vnd.openxmlformats-officedocument.wordprocessingml.template":
            text = ".dotx";
            break;
        case "application/vnd.ms-word.document.macroEnabled.12":
            text = ".docm";
            break;
        case "application/vnd.ms-word.template.macroEnabled.12":
            text = ".dotm";
            break;
        case "application/vnd.ms-excel":
            text = ".xls";
            break;
        case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
            text = ".xlsx";
            break;
        case "application/vnd.openxmlformats-officedocument.spreadsheetml.template":
            text = ".xltx";
            break;
        case "application/vnd.ms-excel.sheet.macroEnabled.12":
            text = ".xlsm";
            break;
        case "application/vnd.ms-excel.template.macroEnabled.12":
            text = ".xltm";
            break;
        case "application/vnd.ms-excel.addin.macroEnabled.12":
            text = ".xlam";
            break;
        case "application/vnd.ms-excel.sheet.binary.macroEnabled.12":
            text = ".xlsb";
            break;
        case "application/vnd.ms-powerpoint":
            text = ".ppt";
            break;
        case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
            text = ".pptx";
            break;
        case "application/vnd.openxmlformats-officedocument.presentationml.template":
            text = ".potx";
            break;
        case "application/vnd.openxmlformats-officedocument.presentationml.slideshow":
            text = ".ppsx";
            break;
        case "application/vnd.ms-powerpoint.addin.macroEnabled.12":
            text = ".ppam";
            break;
        case "application/vnd.ms-powerpoint.presentation.macroEnabled.12":
            text = ".pptm";
            break;
        case "application/vnd.ms-powerpoint.slideshow.macroEnabled.12":
            text = ".ppsm";
            break;
        case "image/jpeg":
            text = ".jpeg";
            break;
        case "image/x-icon":
            text = ".icon";
            break;
        case "image/png":
            text = ".png";
            break;
        case "image/gif":
            text = ".gif";
            break;
    }
    return text;
};

export async function downloadFileByBlobHandler(res,loading) {
    if (res.headers['content-disposition']) {
        isRef(loading) && (loading.value = true)
        const fileNames = res.headers['content-disposition'].split(";");
        let characterSet = fileNames[2].split("filename*=")[1];
        let fileName = decodeURI(fileNames[1].split("filename=")[1], characterSet);  // 下载的文件名
        let blob = new Blob([res.data], {
            type: res.data.type + ";charset=utf-8",
        });
        const url = URL.createObjectURL(blob); // 生成下载链接
        const link = document.createElement("a");
        link.href = url;
        link.download = fileName; // 指定文件名和格式
        document.body.appendChild(link); // 添加下载链接到页面
        link.click(); // 触发下载
        document.body.removeChild(link); //删除下载
        window.URL.revokeObjectURL(url); //释放掉blob对象
        isRef(loading) && (loading.value = false)
    }
}

/**
 * 下载文件
 * @param data    文件流程
 */
export function blobDownload(data) {
    const newFileName = formatDate(new Date(), "yyyyMMddHHmmss");
    let name = newFileName;
    var content = data;
    var datas = new Blob([content], {
        type: "application/vnd.ms-excel;charset=utf-8",
    });
    var downloadUrl = window.URL.createObjectURL(datas);
    var anchor = document.createElement("a");
    anchor.href = downloadUrl;
    anchor.download = name + ".xls";
    anchor.click();
    window.URL.revokeObjectURL(datas);
}